import 'dart:convert';

import 'package:app/api/delivery/index.dart';
import 'package:app/api/dictionary/index.dart';
import 'package:app/components/index.dart';
import 'package:flutter/material.dart';

import '../../util/SecureStorage.dart';

/// 空车呼叫
class Call extends StatefulWidget{
  const Call({super.key});

  @override
  State<Call> createState() => _CallState();
}

/// 空车呼叫
class _CallState extends State<Call>{

  // 车间
  String _workshopName = "";
  // 车间code码
  String _workshopCode = "";
  // AGV类型名
  String _type = "";
  // AGV类型码
  String _agvType = "";
  // 是否携带托盘
  int _radioIndex = 0;
  // agv类型列表
  late List<dynamic> _carTypes;
  // 车间列表
  late List<dynamic> _workshops;

  final FocusNode _firstFocusNode = FocusNode();

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  void scanner(){
  }

  @override
  void initState() {
    super.initState();
    // 加载字典
    loadDictionary();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  /// 加载字典信息
  loadDictionary(){
    SecureStorage.of().get('dictionary').then((res){
      dynamic resultCarType = jsonDecode(res).where((item) => item['code'] == Dictionary.type['carType']).toList();
      dynamic resultWorkshop = jsonDecode(res).where((item) => item['code'] == Dictionary.type['workshop']).toList();
      setState((){
        _carTypes = resultCarType[0]['children'];
        _workshops = resultWorkshop[0]['children'];
      });
    });
  }

  void setValue(key, value){
    switch(key){
      case '_radioIndex': setState(() => _radioIndex = value); break;
      default:
        throw Exception('error key');
    }
  }

  void call(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        Map<String, Object> param = {
          'priority': 1,
          'type': '0',
          'agvType': _agvType,
          'endStation': _workshopCode,
          'isContainer': _radioIndex
        };
        Delivery.of(context).save(param).then((res){
          if(res.data['data']['code'] == 'success'){
            clear();
            Success.of(context).show('空车呼叫成功，请等待');
          }
        });
      }
    });
  }

  /// 展开agv类型
  void onSelectAgvType(){
    Select(
      context: context,
      title: '选择AGV类型',
      list: _carTypes,
      columnNum: 1,
      confirmClick: (selected) => setSelected(selected, '1'),
    ).show();
  }

  /// 选中赋值
  void setSelected(selected, type){
    if(type == '0'){
      Map<String, dynamic> map = _workshops[selected[0]];
      setState((){
        _workshopName = map['name'];
        _workshopCode = map['externalCode'];
      });
    }else if(type == '1'){
      Map<String, dynamic> map = _carTypes[selected[0]];
      setState((){
        _type = map['name'];
        _agvType = map['code'];
      });
    }
  }

  void hideKeyBorder(){
    FocusScopeNode currentFocus = FocusScope.of(context);
    if(!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null){
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void clear(){
    setState(() {
      _agvType = "";
      _type = "";
      _workshopCode = "";
      _workshopName = "";
      _radioIndex = 0;
    });
  }

  /// 选择车间
  void selectWorkshop(){
    Select(
      context: context,
      title: '选择车间',
      list: _workshops,
      columnNum: 1,
      confirmClick: (selected) => setSelected(selected, '0'),
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBars(title: '空车呼叫', context: context),
        body: GestureDetector(
          onTap: hideKeyBorder,
          child: Column(
            children: [
              Group(
                title: '车辆信息',
                width: MediaQuery.of(context).size.width,
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                        formKey: _formKey,
                        formItem: [
                          FormItem(
                            type: 'input',
                            labelText: '车间',
                            placeholder: '请选择车间',
                            focusNode: _firstFocusNode,
                            filedName: 'workshop',
                            iconOnTap: scanner,
                            value: _workshopName,
                            labelWidth: 135,
                            readOnly: true,
                            onClick: selectWorkshop,
                            icon: const Icon(Icons.keyboard_arrow_right),
                            rules: const {'workshop': [{'required': true, 'message': '地码不能为空'}]},
                          ),
                          FormItem(
                            type: 'input',
                            labelWidth: 135,
                            labelText: 'AGV类型',
                            placeholder: '请选择AGV类型',
                            filedName: 'type',
                            iconOnTap: onSelectAgvType,
                            value: _type,
                            readOnly: true,
                            onClick: onSelectAgvType,
                            icon: const Icon(Icons.keyboard_arrow_right),
                            rules: const {'type': [{'required': true, 'message': '请选择类型'}]},
                          ),
                          FormItem(
                            type: 'radioGroup',
                            context: context,
                            radioItem: [
                              RadioItem(
                                  isSelected: _radioIndex == 1,
                                  label: '是',
                                  radioIndex: _radioIndex,
                                  onValueChangedAtIndex: (index, value) => setValue('_radioIndex', 1)),
                              RadioItem(
                                  label: '否',
                                  isSelected: _radioIndex == 0,
                                  radioIndex: _radioIndex,
                                  onValueChangedAtIndex: (index, value) => setValue('_radioIndex', 0)
                              )
                            ],
                            labelWidth: 135,
                            labelText: '是否携带空托盘',
                          ),
                        ]
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 10, right: 10),
                      child: Button(
                        label: '清空',
                        icon: Icons.delete_forever,
                        onPressed: clear,
                        fontColor: Colors.black,
                        backgroundColor: Colors.white,
                        borderColor: const Color.fromARGB(255, 133, 133, 133),
                      ),
                    )
                  ],
                )
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 50, left: 20, right: 20),
                  child: Button(
                    onPressed: call,
                    label: '开始呼叫',
                    height: 60,
                    fontSize: 18,
                  ),
                ),
              ),
            ],
          ),
        ),
    );
  }
}